package com.huawei.chengdu.meetingdemo.view.dialogs;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.device.idea.meeting.Addressbook.model.AddrBookProtocol;
import com.device.idea.meeting.Addressbook.model.AddrBookUserInfo;
import com.device.idea.meeting.CallCtrl.model.CallProtocol;
import com.device.idea.meeting.ConfCtrl.model.AttendeeInfo;
import com.device.idea.meeting.MeetingCallback;
import com.huawei.chengdu.meetingdemo.R;
import com.huawei.chengdu.meetingdemo.consts.ConfConst;
import com.huawei.chengdu.meetingdemo.consts.ObserverConts;
import com.huawei.chengdu.meetingdemo.model.AddrBookBean;
import com.huawei.chengdu.meetingdemo.presenter.ConfSdkPresenter;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;
import com.huawei.chengdu.meetingdemo.presenter.RecordBookPresenter;
import com.huawei.chengdu.meetingdemo.util.AppContext;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.util.ThreadPool;
import com.huawei.chengdu.meetingdemo.view.IViewDataObserver;
import com.huawei.chengdu.meetingdemo.view.adapter.InviteSiteAdapter;
import com.huawei.chengdu.meetingdemo.view.adapter.InviteSiteSelectedAdapter;

import java.util.concurrent.CopyOnWriteArrayList;

public class InviteSiteDialog extends FloatWindowBase implements IViewDataObserver {
    private static final String TAG = InviteSiteDialog.class.getSimpleName();

    private EditText etSearch;

    private RecyclerView rvSites;

    private RecyclerView rvSitesSelected;

    private RelativeLayout rlSelectedEmpty;

    private TextView tvSelectedCount;

    private TextView tvCancel;

    private TextView tvCall;

    private ImageView ivClear;

    private ImageView ivClose;

    private InviteSiteAdapter inviteSiteAdapter;

    private InviteSiteSelectedAdapter selectedAdapter;

    private RecordBookPresenter recordBookPresenter;

    private boolean isCallBtnEnable = false;

    public InviteSiteDialog(@NonNull Context context, int posX, int posY) {
        super(context);
        this.posX = posX;
        this.posY = posY;
        initView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.invite_site_dialog_layout;
    }

    @Override
    protected String getChildName() {
        return TAG;
    }

    @Override
    public void viewDataChanged(int eventId, Object obj) {
        LogUtil.info(TAG + " viewDataChanged , eventId : " + eventId);
        switch (eventId) {
            case ObserverConts.DATA_LOCAL_AND_LDAP_SEARCH_SITE:
                searchAddrCallBack();
                break;
            case ObserverConts.DATA_LOCALSITEANDGROUP_CHANGE:
                searchAddrBook(etSearch.getText().toString().trim(), false);
                break;
            case ObserverConts.LOCAL_CHAIR_RELEASED_MSG:
                release();
                break;
            default:
                break;
        }
    }

    @Override
    public void unRegisterListenService() {
        recordBookPresenter.unregistDataChangeListenerObj(this);
        MeetingManager.getInstance().unregistDataChangeListenerObj(this);
    }

    @Override
    public void registerListenerService() {
        recordBookPresenter.registerAddressObserved(ObserverConts.DATA_LOCAL_AND_LDAP_SEARCH_SITE, this);
        recordBookPresenter.registerAddressObserved(ObserverConts.DATA_LOCALSITEANDGROUP_CHANGE, this);
        MeetingManager.getInstance().registerObserved(ObserverConts.LOCAL_CHAIR_RELEASED_MSG, this);
    }

    public InviteSiteSelectedAdapter getSelectedAdapter() {
        return selectedAdapter;
    }

    public InviteSiteAdapter getInviteSiteAdapter() {
        return inviteSiteAdapter;
    }

    @Override
    public void release() {
        unRegisterListenService();
        super.release();
    }

    private void initView() {
        LogUtil.info(TAG + " initView");
        recordBookPresenter = AppContext.instance().rbServ;
        etSearch = mRootView.findViewById(R.id.et_search);
        ivClear = mRootView.findViewById(R.id.iv_clear_input);
        ivClose = mRootView.findViewById(R.id.iv_close);
        rvSites = mRootView.findViewById(R.id.rv_sites_result);
        rvSitesSelected = mRootView.findViewById(R.id.rv_site_selected);
        rlSelectedEmpty = mRootView.findViewById(R.id.rl_select_empty_tip);
        tvSelectedCount = mRootView.findViewById(R.id.tv_selected_site_count);
        tvCall = mRootView.findViewById(R.id.tv_call);
        tvCancel = mRootView.findViewById(R.id.tv_cancel);

        dlgWidth = (int) mContext.getResources().getDimension(R.dimen.def_dimens_2048);
        dlgHeight = (int) mContext.getResources().getDimension(R.dimen.def_dimens_1484);
        int gravity = Gravity.BOTTOM | Gravity.START;
        int xCoordinate = posX - dlgWidth / 2;
        int yCoordinate = posY + ConfConst.BOTTOM_CONF_HEIGHT + ConfConst.COMMON_MARGIN_Y;
        super.setWmPositionParams(gravity, xCoordinate, yCoordinate, dlgWidth, dlgHeight);

        updateSelectedCount(0);
        updateCallBtnStatus();
        initRecyclerView();
        initEvent();
        registerListenerService();
    }

    /**
     * 更新已选择区域背景
     *
     * @param selectedCount 已选择的地址本条目数
     */
    public void updateSelectedBgr(int selectedCount) {
        updateSelectedCount(selectedCount);
        isCallBtnEnable = (selectedCount > 0);

        rlSelectedEmpty.setVisibility(isCallBtnEnable ? View.GONE : View.VISIBLE);
        updateCallBtnStatus();
    }

    private void updateSelectedCount(int count) {
        String str = mContext.getString(R.string.invite_site_selected);
        String text = String.format(str, "" + count);
        tvSelectedCount.setText(text);
    }

    private void updateCallBtnStatus() {
        tvCall.setEnabled(isCallBtnEnable);
        tvCall.setBackgroundResource(isCallBtnEnable ? R.drawable.quite_button_bg : R.drawable.quite_button_unenable);
    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        rvSites.setLayoutManager(layoutManager);
        rvSitesSelected.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        inviteSiteAdapter = new InviteSiteAdapter(mContext, this);
        selectedAdapter = new InviteSiteSelectedAdapter(mContext, this);
        rvSites.setAdapter(inviteSiteAdapter);
        rvSitesSelected.setAdapter(selectedAdapter);
        inviteSiteAdapter.notifyDataSetChanged();
        selectedAdapter.notifyDataSetChanged();
    }

    private void initEvent() {
        ivClose.setOnClickListener(view -> release());
        ivClear.setOnClickListener(view -> handleClear());
        tvCancel.setOnClickListener(view -> handleCancel());
        tvCall.setOnClickListener(view -> handleCall());
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence seq, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence seq, int start, int before, int count) {
                String inputStr = etSearch.getText().toString().trim();
                updateDelBtnStatus(!TextUtils.isEmpty(inputStr));
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputStr = etSearch.getText().toString().trim();
                searchAddrBook(inputStr, false);
            }
        });
        etSearch.setOnFocusChangeListener((view, isHasFocus) -> etSearch.setCursorVisible(isHasFocus));
    }

    /**
     * 初始化数据
     */
    public void initData() {
        LogUtil.info(TAG + " initData");
        searchAddrBook("", true);
    }

    private void searchAddrBook(String keyWord, boolean isAutoFlag) {
        LogUtil.info(TAG + " searchAddrBook,keyWord=" + keyWord + ",isAutoFlag=" + isAutoFlag);
        inviteSiteAdapter.setKeyWord(keyWord);
        MeetingManager.getInstance().startSearchSite(keyWord, isAutoFlag);
    }

    private void handleClear() {
        etSearch.getText().clear();
    }

    private void handleCancel() {
        LogUtil.info(TAG + " handleCancel()");
        selectedAdapter.clearSelectedSite();
    }

    private void handleCall() {
        LogUtil.info(TAG + " handleCall()");
        if (!isCallBtnEnable) {
            return;
        }
        CopyOnWriteArrayList<AddrBookBean> selectedBeans = selectedAdapter.getSelectedSiteList();
        ThreadPool.getInstance().submit(() -> startCall(selectedBeans));
        Toast.makeText(mContext, R.string.adding_participant,
                Toast.LENGTH_LONG).show();
        release();
    }

    private void startCall(CopyOnWriteArrayList<AddrBookBean> selectedBeans) {
        int callBackIndex = 0;
        for (AddrBookBean selectedBean : selectedBeans) {
            AttendeeInfo attendeeInfo = new AttendeeInfo();
            attendeeInfo.setSiteName(selectedBean.getName());
            attendeeInfo.setRate(selectedBean.getCallRate());
            attendeeInfo.setProtocol(selectedBean.getCallProtocol());
            if (selectedBean.isAddHandle()) { // 临时地址本， 视频+AUTO
                attendeeInfo.setProtocol(CallProtocol.AUTO);
            }
            attendeeInfo.setSiteNumber(selectedBean.getSiteNumber());
            attendeeInfo.setSiteIp(selectedBean.getIP());
            attendeeInfo.setSiteUri(selectedBean.getUrl());
            int finalCallBackIndex = callBackIndex;
            LogUtil.info(TAG + " handleCall() , rate : " + attendeeInfo.getRate());
            ConfSdkPresenter.addSite(attendeeInfo, new MeetingCallback<Integer>() {
                        @Override
                        public void onSuccess(Integer succMsg) {
                            LogUtil.info(TAG + " startCall onSuccess,index=" + finalCallBackIndex);
                        }

                        @Override
                        public void onFailed(int errCode, String errMsg) {
                            LogUtil.info(TAG + " startCall onFailed,errCode=" + errCode + ",errMsg=" + errMsg + ",index=" + finalCallBackIndex);
                        }
                    });
            callBackIndex++;
        }
    }

    private void updateDelBtnStatus(boolean isEnableShow) {
        ivClear.setVisibility(isEnableShow ? View.VISIBLE : View.GONE);
    }

    private void searchAddrCallBack() {
        CopyOnWriteArrayList<AddrBookBean> allSites = recordBookPresenter.searchAddrBookUserList;
        LogUtil.info(TAG + " searchAddrCallBack(), result size : " + allSites.size());
        String keyWord = etSearch.getText().toString().trim();
        // 表示在搜索结果为空时，自己添加的临时LDAP
        if (!TextUtils.isEmpty(keyWord) && allSites.size() <= 0) {
            AddrBookUserInfo userInfo = new AddrBookUserInfo();
            userInfo.setName(keyWord);
            userInfo.getLineInfo().setSiteNumber(keyWord);
            userInfo.getLineInfo().setUrl(keyWord);
            userInfo.getLineInfo().setIp(keyWord);
            userInfo.setLineType(AddrBookProtocol.SIP);
            userInfo.getLineInfo().setCallRate(ConfConst.DFT_CALL_WIDTH);
            AddrBookBean site = new AddrBookBean(userInfo);
            site.setAddHandle(true);
            allSites.add(site);
            AddrBookBean tempAddrBean = allSites.get(0);
            tempAddrBean.setChecked(false);
        }
        inviteSiteAdapter.setData(allSites);
    }
}
